//
//  HTTPTool.m
//  268EDU_Demo
//
//  Created by LiuXing on 2017/3/27.
//  Copyright © 2017年 edu268. All rights reserved.
//

#import "HTTPTool.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
#import "ReactiveCocoa.h"

@implementation HTTPTool

+ (RACSignal *)getWithURL:(NSString *)urlString withParamater:(NSDictionary *)paramter {
    // 添加hud
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject] animated:YES];
    hud.label.text = @"正在加载ing";
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.animationType = MBProgressHUDAnimationFade;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 5;
    RACSubject *sub = [ RACSubject subject];
    [manager GET:urlString parameters:paramter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [sub sendNext:@{@"code":@100, @"data":responseObject}];
        [sub sendCompleted];
        [hud hideAnimated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [sub sendNext:@{@"code":@-400, @"data":@"请求失败"}];
        [sub sendCompleted];
        hud.label.text = @"请求失败, 重新发送请求";
        [hud hideAnimated:YES];
    }];
    return sub;
}

+ (RACSignal *)postWithURL:(NSString *)urlString withParamater:(NSDictionary *)parameter {
    // 添加hud
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].windows lastObject] animated:YES];
    hud.label.text = @"正在加载ing";
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    hud.animationType = MBProgressHUDAnimationFade;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    RACSubject *sub = [ RACSubject subject];
    [manager POST:urlString parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [sub sendNext:responseObject];
        [sub sendCompleted];
        
        [hud hideAnimated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
        [sub sendNext:@{@"code":@-400}];
        [sub sendCompleted];
        hud.label.text = @"请求失败, 重新发送请求";
        [hud hideAnimated:YES];
    }];
    return sub;
}

@end
